package com.pai4j.zwiki.controller;

import com.pai4j.zwiki.dto.QaRequest;
import com.pai4j.zwiki.dto.QaResponse;
import com.pai4j.zwiki.service.QaService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 问答控制器
 * 处理交互式问答相关的HTTP请求
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/qa")
@RequiredArgsConstructor
public class QaController {

    private final QaService qaService;

    /**
     * 提问接口
     */
    @PostMapping("/ask")
    public ResponseEntity<Map<String, Object>> askQuestion(@Valid @RequestBody QaRequest request) {
        log.info("收到问答请求, 任务ID: {}, 问题: {}", request.getTaskId(), request.getQuestion());
        
        try {
            QaResponse response = qaService.answerQuestion(request.getTaskId(), request.getQuestion());
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "回答成功");
            result.put("data", response);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("回答问题失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "回答失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 构建项目索引
     */
    @PostMapping("/index/{taskId}")
    public ResponseEntity<Map<String, Object>> buildIndex(@PathVariable String taskId) {
        log.info("构建项目索引: {}", taskId);
        
        try {
            qaService.buildProjectIndex(taskId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "索引构建成功");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("构建索引失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "索引构建失败");
            
            return ResponseEntity.internalServerError().body(result);
        }
    }
}

